﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Security;
using System.Security.Claims;
using Microsoft.IdentityModel.Tokens;
using Microsoft.Extensions.Options;
using System.Text;
using System.IdentityModel.Tokens.Jwt;

namespace AuthenticationCenter.Utility
{
  public class CustomHSJWTService : ICustomJWTService
  {
    private readonly JWTTokenOptions _JWTTokenOptions;
    public CustomHSJWTService(IOptionsMonitor<JWTTokenOptions> jwtTokenOptions)
    {
      this._JWTTokenOptions = jwtTokenOptions.CurrentValue;
    }
    public string GetToken(string UserName, string password)
    {
      //有效载荷
      var claims = new[]
       {
               new Claim(ClaimTypes.Name, UserName),
               new Claim("NickName",UserName),
               new Claim("Role","Administrator"),//传递其他信息   
        };
      //加密需要加密key
      SymmetricSecurityKey key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_JWTTokenOptions.SecurityKey));
      SigningCredentials creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
      JwtSecurityToken token = new JwtSecurityToken(
        issuer: _JWTTokenOptions.Issuer,
        audience: _JWTTokenOptions.Audience,
        claims: claims,
        expires: DateTime.Now.AddMinutes(1),
        signingCredentials: creds
        );
      return new JwtSecurityTokenHandler().WriteToken(token);
    }
  }
}
